package com.lv.suyiyong.hfrwork.ui

import android.Manifest
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ScreenUtils
import com.chad.library.adapter.base.listener.OnItemDragListener
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lihang.ShadowLayout
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lv.common.base.BaseActivity
import com.lv.common.bean.FactoryBorderBeans
import com.lv.common.bean.FindFactoryBorderBean
import com.lv.common.imp.ItemTouchHelperViewHolder
import com.lv.common.imp.OnPositionTListener
import com.lv.common.utils.*
import com.lv.common.utils.picengine.CompressEngine
import com.lv.common.utils.picengine.GlideEngine
import com.lv.service.bean.DisplayFacBean
import com.lv.service.bean.TVIVItemBean
import com.lv.service.bean.ViewTypeStringBean
import com.lv.suyiyong.hfrwork.R
import com.lv.suyiyong.hfrwork.adapter.ManagerFactoryAdapter
import com.lv.suyiyong.hfrwork.databinding.ActivityCompanyShowFactoryBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException

/**
 * 作者： ygx
 * 创建日期：2023/6/6 3:52 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：开户 工厂展示
 */
@Route(path = ARoutUtils.ShowFactoryActivity)
class ShowFactoryActivity : BaseActivity<ActivityCompanyShowFactoryBinding>(),
    OnClickListener {
    @Autowired(name = "items")
    @JvmField
    var mIntentData: ArrayList<DisplayFacBean>? = null

    @Autowired(name = "expird")
    @JvmField
    var mExpird: String = "0"//0 免费


    private var mCutW = 0
    private var mCutH = 0

    //    private var mCpyid: String? = YgxSpUtils.getString(Constants.KEY_CPYID)
    private val mBeans = mutableListOf<TVIVItemBean>()
    private val mPopBeans = mutableListOf<FactoryBorderBeans>()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private var mAdapter: ManagerFactoryAdapter? = null
    private var mFacoryDatas = mutableListOf<ViewTypeStringBean>()

    private var mVideoCount = 0
    private var mImageCount = 0
    private var mVideoMedia: LocalMedia? = null
//    private var mSwitch = false
//    private var mSubFactoryBorderItemBean = FactoryBorderItemBean(
//        "18",
//        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/1231/newkuang/7-1-1.png",
//        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/1231/newkuang/7-1.png",
//        "upleft",
//        "293",
//        "105",
//        "1",
//        "D2D2D2",
//        "0",
//        "5",isspecially = "0"
//    )

    override fun getLayoutRes() = R.layout.activity_company_show_factory
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@ShowFactoryActivity, titleBar)
            titleBar.setTitle("工厂展示")
            titleBar.onClickBackIcon { finish() }
            viewImg.setOnClickListener(this@ShowFactoryActivity)
//            ivSwitch.setOnClickListener(this@ShowFactoryActivity)
            tvSave.setOnClickListener(this@ShowFactoryActivity)
        }

    }

    private fun checkPermission() {
        val permissions = mutableListOf(
            Manifest.permission.CAMERA,
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.READ_MEDIA_IMAGES)
//            permissions.add(Manifest.permission.READ_MEDIA_AUDIO)
            permissions.add(Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }

        PermissionXUtils.checkPermissBefore(
            this@ShowFactoryActivity,
            permissions,
            "请授予相机、存储权限，以便使用相机拍摄或在手机相册中选择图片",
            callback = object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>
                ) {
                    if (allGranted) {
                        showPicSelector()
                    }
                }
            })
    }

    private fun showPicSelector() {
//        val count = if (isVideo) 1 else 0
//        val countMax = if (isVideo) 1 else 5 - mBeans.size
//        val openGallery = if (isVideo) SelectMimeType.ofVideo() else SelectMimeType.ofImage()

        PictureSelector.create(this@ShowFactoryActivity)
            .openGallery(SelectMimeType.ofAll())//图库显示的类型
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(CompressEngine.createCompressEngine())
//            .setCropEngine(CropWHEngine.createCropEngine())
            .setMaxSelectNum(6 - mBeans.size)//最大数
            .setMaxVideoSelectNum(1 - mVideoCount)//最大视频数
//            .setMinSelectNum(2)
            .setImageSpanCount(4)
            .isMaxSelectEnabledMask(true)//不可点击时，是否显示朦层
            .isPreviewImage(true) // 是否可预览图片
            .isDisplayCamera(true) // 是否显示拍照按钮
            .isOriginalSkipCompress(true) // 是否压缩
            .setRecordVideoMaxSecond(30)
//            .setSelectedData(mBeans)
            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            .isWithSelectVideoImage(true)//是否可以同时选择视频和图片
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    if (!result.isNullOrEmpty()) {
                        var pathVideo = ""
                        var pathCut = false
                        result.forEach { item ->
                            val mimeType = item?.mimeType ?: ""
                            if (mimeType.contains("video")) {
                                pathVideo = item?.compressPath ?: item?.realPath ?: ""
                                mCutW = item?.width ?: ScreenUtils.getScreenWidth()
                                mCutW = item?.height ?: ScreenUtils.getScreenWidth()
                                val duration = item?.duration ?: 0L
                                if (duration < 30 * 1000L) {
                                    mVideoMedia = item
                                    mVideoCount++
//                                    mSubFactoryBorderItemBean.isRegularSize =
//                                        if (mSwitch) "0" else "1"
//                                    val border =
//                                        GsonUtils.toJson(mSubFactoryBorderItemBean)
                                    mBeans.add(
                                        0,
                                        TVIVItemBean(
                                            pathVideo,
                                            "1",
                                            item,
                                            (item?.width
                                                ?: ScreenUtils.getScreenWidth()).toString(),
                                            height = (item?.height
                                                ?: ScreenUtils.getScreenWidth()).toString(),
//                                            border = border
                                        )
                                    )
                                } else {
                                    pathCut = true
                                }
                            } else {
                                mImageCount += 1
//                                mSubFactoryBorderItemBean.isRegularSize =
//                                    if (mSwitch) "0" else "1"
//                                val border = GsonUtils.toJson(mSubFactoryBorderItemBean)
                                mBeans.add(
                                    TVIVItemBean(
                                        item?.compressPath ?: item?.realPath ?: "",
                                        "0",
                                        item,
                                        (item?.width
                                            ?: ScreenUtils.getScreenWidth()).toString(),
                                        height = (item?.height
                                            ?: ScreenUtils.getScreenWidth()).toString(),
//                                        border = border
                                    )
                                )
                            }
                            mAdapter?.notifyDataSetChanged()

//                                        mBinding.llSwith.visibility =
//                                            if (mBeans.size > 0) View.VISIBLE else View.GONE
                            mBinding.imageSize = mImageCount


                        }
//                        swithHeight()
                        if (pathVideo.isNotEmpty() && pathCut) {
                            ARouter.getInstance()
                                .build(ARoutUtils.EditorVideoCutActivity)
                                .withString("mMediaUrl", pathVideo)
                                .navigation(this@ShowFactoryActivity, 1)

//                            ARouter.getInstance()
//                                .build(ARoutUtils.VideoEditorActivity)
//                                .withString("videoPath", pathVideo)
//                                .navigation(this@ShowFactoryActivity, 1)
                        }
                    }

                }

                override fun onCancel() {}
            })


    }

    override fun initData() {
        super.initData()
        object : Thread() {
            override fun run() {
                super.run()
                FindBorder()
            }
        }.start()
    }

    override fun initConfig() {
        super.initConfig()
        initRecyclerView()
        mIntentData?.forEach { item ->
            val url = item.image ?: ""

            if (item.type == "1") {
                mVideoCount += 1
                val localMedia = LocalMedia()
                localMedia.compressPath = url
                localMedia.realPath = url
                localMedia.path = url
                if (url.startsWith("http")) {
                    val (width, height, wh) = YgxUtilsKt.getImageWH(url, 236.0f)
                    localMedia.width = width.toInt()
                    localMedia.height = height.toInt()
                }
                mVideoMedia = localMedia
                mBeans.add(
                    0,
                    TVIVItemBean(
                        url, item.type ?: "1", mVideoMedia, item.type, item.width, item.height,
//                        item.border
                    )
                )

            } else {
                mImageCount += 1
                mBinding.imageSize = mImageCount
                val localMedia = LocalMedia()
                localMedia.compressPath = url
                localMedia.realPath = url
                localMedia.path = url
                if (url.startsWith("http")) {
                    val (width, height, wh) = YgxUtilsKt.getImageWH(url, 236.0f)
                    localMedia.width = width.toInt()
                    localMedia.height = height.toInt()
                }
                mBeans.add(
                    TVIVItemBean(
                        url, item.type ?: "0", localMedia, item.type, item.width, item.height,
//                        item.border
                    )
                )

            }
        }
        mAdapter?.notifyDataSetChanged()

    }


    private fun initRecyclerView() {
        mAdapter = ManagerFactoryAdapter(mBeans, mExpird)
        mBinding.rvContent.adapter = mAdapter
        mAdapter?.setHeight(132)
        mAdapter?.draggableModule?.isDragEnabled = true
        mAdapter?.draggableModule?.setOnItemDragListener(object : OnItemDragListener {
            //拖拽开始
            override fun onItemDragStart(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
                mBinding.tvSave.isEnabled = false
                val shadowLayout =
                    viewHolder?.itemView?.findViewById<ShadowLayout>(R.id.shadow_layout)
                val clParent = viewHolder?.itemView?.findViewById<ConstraintLayout>(R.id.cl_parent)
                if (viewHolder is ItemTouchHelperViewHolder) {
                    val itemViewHolder = viewHolder as ItemTouchHelperViewHolder
                    itemViewHolder.onItemSelected(shadowLayout)
                    clParent?.scaleY = 0.94f
                }
            }

            /**
             * 因拖拽而发生位置互换时回调
             * @param source    非用户拖拽的那个改变位置的Item
             * @param from    用户拖拽的Item换位之前的position
             * @param target    用户拖拽的Item
             * @param to    用户拖拽的Item换位之后的position
             */
            override fun onItemDragMoving(
                source: RecyclerView.ViewHolder?,
                from: Int,
                target: RecyclerView.ViewHolder?,
                to: Int
            ) {

            }

            //拖拽结束
            override fun onItemDragEnd(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
                val shadowLayout =
                    viewHolder?.itemView?.findViewById<ShadowLayout>(R.id.shadow_layout)
                val clParent = viewHolder?.itemView?.findViewById<ConstraintLayout>(R.id.cl_parent)

                if (viewHolder is ItemTouchHelperViewHolder) {
                    val itemViewHolder = viewHolder as ItemTouchHelperViewHolder
                    itemViewHolder.onItemClear(shadowLayout)
                    clParent?.scaleY = 1.0f

                }
                val intList = mBeans.withIndex().filter { it.value.type == "1" }.map { it.index }
                if (intList.isNotEmpty()) {
                    if (intList[0] != 0) {
                        showToast("视频必须放在最前面")
                        val get = intList.get(0)
                        val tvivItemBean = mBeans[get]
                        mBeans.removeAt(get)
                        mBeans.add(0, tvivItemBean)
                        mAdapter?.notifyDataSetChanged()
                        mBinding.tvSave.isEnabled = true
                    } else {
                        mBinding.tvSave.isEnabled = true
                    }
                } else {
                    mBinding.tvSave.isEnabled = true
                }
            }
        })
    }


    override fun initEvents() {
        super.initEvents()
        mAdapter?.onViewDeleteClickListener = OnPositionTListener { position, data ->
            if (data.type == "1") {
                mVideoCount -= 1
                mVideoMedia = null
            } else {
                mImageCount -= 1
                mBinding.imageSize = mImageCount
            }
//            mImgBeans.removeAt(position)
            mBeans.removeAt(position)
            mAdapter?.notifyItemRemoved(position)
            mAdapter?.notifyItemRangeChanged(position, mBeans.size)
//            mBinding.llSwith.visibility = if (mBeans.size > 0) View.VISIBLE else View.GONE

        }
        mAdapter?.onViewClickListener = OnPositionTListener { position, data ->
//            if (mExpird == "0") {
            mFacoryDatas.clear()
            for (i in 0 until mBeans.size) {
                val tvivItemBean = mBeans[i]
                val type = tvivItemBean.type
                var mType = ViewTypeStringBean.PIC_TYPE
                if (type == "1") {
                    mType = ViewTypeStringBean.VEDIO_TYPE
                }
                mFacoryDatas.add(
                    ViewTypeStringBean(
                        tvivItemBean.image?.realPath ?: "",
                        mType
                    )
                )
            }
            val json = GsonUtils.toJson(mFacoryDatas)
            ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
                .withInt("position", position)
                .withString("data", json)
                .navigation()
//            } else {
//                showBorderDialog(position)
//            }


        }
    }


    override fun onResume() {
        super.onResume()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
//            R.id.iv_switch -> {
//                mSwitch = !mSwitch
//                mBinding.ivSwitch.setImageResource(if (mSwitch) com.lv.common.R.drawable.icon_switch_on else com.lv.common.R.drawable.icon_switch_off)
//                swithHeight()
//            }
            R.id.view_img -> {
                checkPermission()
            }
//            R.id.iv_video -> {
//                mFacoryDatas.clear()
////
//                mFacoryDatas.add(ViewTypeStringBean(mVideoMedia?.realPath ?: "", 1))
//                val json = GsonUtils.toJson(mFacoryDatas)
//                ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
//                    .withInt("position", 0)
//                    .withString("data", json)
//                    .navigation()
//            }
//            R.id.iv_video_clear -> {
//                mVideoCount = 0
//                mVideoMedia = null
//                mBinding.ivPlay.visibility = View.GONE
//                mBinding.ivVideo.visibility = View.GONE
//                mBinding.ivVideoClear.visibility = View.GONE
//            }

            R.id.tv_save -> {
//                if (mVideoMedia != null) {
//                    mBeans.add(TVIVItemBean(mVideoMedia?.realPath ?: "", "1", mVideoMedia))
//                }
                if (mBeans.isEmpty()) {
                    showToast("请选择工厂展示图片")
                } else {
                    val beans = ArrayList<TVIVItemBean>()
                    beans.addAll(mBeans)
                    val bundle = Bundle()
                    bundle.putParcelableArrayList("media", beans)
                    intent.putExtras(bundle)
                    setResult(RESULT_OK, intent)
                    finish()
                }

            }

        }
    }

    private fun FindBorder() {
        val client = OkHttpClient()
        //创建请求连接，url里面存放请求连接，get表示其实get请求
        val request: Request =
            Request.Builder().url(Constants.ADDRESS_NET_FACTORY_BORDER).get().build()
        try {
            //使用execute()方法执行请求
            val response = client.newCall(request).execute()
            //定义字符串接收请求信息
            val result = response.body?.string()
            parseData(result)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun parseData(result: String?) {
        val listType = object : TypeToken<FindFactoryBorderBean>() {}.type
        val datas: FindFactoryBorderBean = Gson().fromJson(result, listType)
        datas.let {
            val factoryBorderBeans = it.data
            factoryBorderBeans?.let {
                mPopBeans.addAll(factoryBorderBeans)
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                1 -> {
                    val stringExtra = data.getStringExtra("PARAMS_CROP_RESULT_PATH")
                    val duration = data.getFloatExtra("duration", 0.0f)

//                data?.getBundleExtra("")
//                    val localMedia: LocalMedia? = data.getParcelableExtra("media")
                    if (!stringExtra.isNullOrEmpty()) {
                        mVideoCount += 1
                        val localMedia = LocalMedia()
                        localMedia.compressPath = stringExtra
                        localMedia.path = stringExtra
                        localMedia.realPath = stringExtra
                        localMedia.duration = duration.toLong()
                        mVideoMedia = localMedia
                        val width = mCutW
                        val height = mCutH

                        mBeans.add(
                            0,
                            TVIVItemBean(
                                localMedia.compressPath, "1", localMedia, width = width.toString(),
                                height = height.toString()
                            )
                        )
                        mAdapter?.notifyDataSetChanged()
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}